package com.yt.ds.chapter3;

/**
 * @Author: lzf
 * @Date: 2020/7/25 14:31
 * @Description: 基于拉链法的散列表
 */
public class SeparateChainingHashST<Key, Value> {
    private int n;      // 键值对数
    private int m;      // 散列表大小
    private SequentialSearchST<Key, Value>[] st;

    public SeparateChainingHashST() {
        this(997);
    }

    public SeparateChainingHashST(int m) {
        this.m = m;
        st = (SequentialSearchST<Key, Value>[]) new SequentialSearchST[m];
        for (int i = 0; i < m; i++) {
            st[i] = new SequentialSearchST();
        }
    }

    /**
     * 哈希code
     */
    private int hash(Key key) {
        return (key.hashCode() & 0x7fffffff) % m;
    }

    /**
     * 取值
     */
    public Value get(Key key) {
        int i = hash(key);
        return st[i].get(key);
    }

    /**
     * 设置
     */
    public void put(Key key, Value value) {
        int i = hash(key);
        st[i].put(key, value);
    }
}
